<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /**
       * @param {string} s
       * @return {number}
       */
      var myAtoi = function (s) {
        var isPositive = 1; // 判断正负
        var nums = []; // 保存数字的数组
        var sum = 0; // 最终解析的结果
        var isStartNumber = false; // 数字读取完毕的标记
        for (var i = 0; i < s.length; i++) {
          if (isStartNumber) break;
          // 空格跳过
          if (s[i] === " ") continue;

          // 开头遇到除空格 正/负号 数字的其他字符  Number('-')=NaN
          if (!(s[i] === "-" || s[i] === "+") && isNaN(Number(s[i]))) {
            return 0;
          }

          // 判+/-负号
          if (s[i] === "-" || s[i] === "+") {
            isPositive = s[i] === "-" ? -1 : 1;
            // 判断+/-号下一个是不是数字
            if (s[i + 1] === " " || isNaN(Number(s[i + 1]))) {
              return 0;
            }
          }

          // 开始有数字
          if (!isNaN(Number(s[i])) && s[i] !== " ") {
            // 判断下一个空格或其他字符   isNaN(Number(' ') = false
            if (isNaN(Number(s[i + 1])) || s[i + 1] === " ") {
              isStartNumber = true;
            }
            nums.unshift(Number(s[i]));
          }
        }

        for (var i = 0; i < nums.length; i++) {
          sum += nums[i] * 10 ** i;
        }
        // 
        if (sum >= 2 ** 31) {
          // isPositive取值为正负1；-1加1就为0
          sum = isPositive + 1 ? 2 ** 31 - 1 : 2 ** 31;
        }
        return isPositive * sum;
      };

      var s = "+ 12 2a 65653456345634354356";
      console.log(myAtoi(s));
    </script>
  </body>
</html>
